package com.yupi.yupicturebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupicturebackend.Exception.BusinessException;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.Exception.ThrowUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.yupicturebackend.model.dto.*;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceLevelEnum;
import com.yupi.yupicturebackend.model.vo.SpaceVO;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
@Slf4j
public class SpaceController {

    @Resource
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private UserService userService;
    
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest==null,ErrorCode.PARAMS_ERROR,"空间参数异常");

        User loginUser = userService.getLoginUser(request);

        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);


        return ResultUtils.success(spaceId);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // 判断是否登陆
        Long userId = user.getId();
        ThrowUtils.throwIf(userId == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登陆！");
        // 判断照片是否存在
        Long SpaceId = deleteRequest.getId();
        Space oldSpace = spaceService.getById(SpaceId);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在！");
        // 只有管理员可以删除
        Space space = spaceService.getById(SpaceId);
        spaceService.checkSpaceAuth(user, space);
        // 操作数据库
        boolean success = spaceService.removeById(SpaceId);

        ThrowUtils.throwIf(!success, ErrorCode.OPERATION_ERROR, "删除空间失败！");

        return ResultUtils.success(true);
    }

    /**
     * 根据id获取空间（包装类）
     */
    @PostMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(@RequestParam("id") Long id, HttpServletRequest request) {
        // 判断是否登陆
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "用户未登陆");
        Space Space = spaceService.getById(id);
        ThrowUtils.throwIf(Space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在！");
        return ResultUtils.success(Space);
    }


    /**
     * vo类
     */
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(spaceVO);
    }


    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest SpaceQueryRequest, HttpServletRequest request) {
        long current = SpaceQueryRequest.getCurrent();
        long size = SpaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> SpacePage = spaceService.page(new Page<>(current, size),spaceService.getQueryWrapper(SpaceQueryRequest));
        return ResultUtils.success(SpacePage);
    }

    /**
     * 分页查询接口
     * 该接口用于获取空间列表的分页查询结果，根据用户请求的页码和页大小进行查询
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> getSpaceVOPage(@RequestBody SpaceQueryRequest SpaceQueryRequest, HttpServletRequest request) {
        // 获取当前页码
        long current = SpaceQueryRequest.getCurrent();
        // 获取当前页大小
        long size = SpaceQueryRequest.getPageSize();
        // 限制爬虫：如果请求的页大小超过20条，则视为异常请求，可能是爬虫行为
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库：根据当前页码和页大小，以及查询条件，从数据库中获取空间数据
        Page<Space> SpacePage = spaceService.page(new Page<>(current, size), spaceService.getQueryWrapper(SpaceQueryRequest));
        // 返回成功响应，包含分页查询结果
        return ResultUtils.success(spaceService.getSpaceVOPage(SpacePage, request));
    }


    /**
     * 编辑空间（用户可用)
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest SpaceEditRequest, HttpServletRequest request) {

        if (SpaceEditRequest == null || SpaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常");
        }
        // 实体类与dto转换
        Space space = new Space();
        BeanUtils.copyProperties(SpaceEditRequest, space);
        // 设置编辑时间
        space.setEditTime(new Date());
        // 数据校验
        spaceService.validSpace(space,false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        Long oldSpaceId = SpaceEditRequest.getId();
        Space oldSpace = spaceService.lambdaQuery().eq(Space::getId, oldSpaceId).one();
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        // 仅本人或管理员可编辑 -> 既不是本人也不是管理员不可以编辑
        spaceService.checkSpaceAuth(loginUser, oldSpace);
        // 操作数据库
        boolean success = spaceService.updateById(space);
        ThrowUtils.throwIf(!success, ErrorCode.OPERATION_ERROR, "编辑空间失败");
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest SpaceUpdateRequest, HttpServletRequest request) {
        if (SpaceUpdateRequest == null || SpaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常");
        }
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登陆！");

        // 实体类与dto转换
        Space space = new Space();
        BeanUtils.copyProperties(SpaceUpdateRequest, space);
        // 设置编辑时间
        space.setEditTime(new Date());

        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 校验数据
        spaceService.validSpace(space,false);
        // 判断是否存在
        Long SpaceId = space.getId();
        Space oldSpace = spaceService.lambdaQuery().eq(Space::getId, SpaceId).one();
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        Space newSpace = new Space();
        BeanUtils.copyProperties(SpaceUpdateRequest, newSpace);

        boolean success =spaceService.updateById(newSpace);
        ThrowUtils.throwIf(!success, ErrorCode.OPERATION_ERROR, "更新空间失败");
        return ResultUtils.success(true);
    }

    /**
     * 获取所有空间等级
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceByLevel() {

        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());

        return ResultUtils.success(spaceLevelList);
    }


}
